// selectionUtils.js (数据选择、筛选、计数、排序逻辑)
import store from '@/store';
// 标记是否为初次加载
let isInitialLoad = true;
import { cloneDeep, orderBy } from 'lodash';
/**
 * 更新下拉选项的函数
 * @param {Array} subjectData - 主题数据
 * @param {Ref} xkType - 当前学科类型
 */
// 更新下拉选项的函数
export const updateDropdownOptions = (
  isMajor,
  ruleType,
  subjectData,
  xkType,
) => {
  const { selectCollegeList, selectMarjorList } = store.getters.znxkInfo;
  if (!Array.isArray(subjectData) || !subjectData.length) return;

  // 深拷贝并重置 disabled 状态
  let processedData = cloneDeep(subjectData).map((item) => ({
    ...item,
    disabled: false,
  }));

  // 根据规则对数据进行排序
  processedData = sortProcessedData(processedData, ruleType);

  // 获取筛选后的列表
  const zyORyxList = extractAndFilter(
    isMajor ? selectMarjorList : selectCollegeList,
  );

  // 特殊的 xkType 排序逻辑
  if (shouldReorderForXkType(xkType, ruleType, processedData)) {
    processedData = reorderForXkType(processedData, zyORyxList);
  }
  return processedData.slice(0, 3);
};

// 排序逻辑：根据初次加载或 chooseNum 进行排序
const sortProcessedData = (data, ruleType) => {
  if (Number(ruleType) !== 0) return data;
  const allChooseNumZero = data.every((item) => item.chooseNum == 0);

  if (isInitialLoad || allChooseNumZero) {
    data = orderBy(data, ['id'], ['asc']);
    isInitialLoad = false;
  } else {
    data = orderBy(data, ['chooseNum'], ['desc']);
  }
  return data;
};

// 判断是否需要特殊 xkType 排序
const shouldReorderForXkType = (xkType, ruleType, data) => {
  const allChooseNumZero = data.every((item) => item.chooseNum == 0);
  return xkType == 3 && !allChooseNumZero && ruleType == 0;
};

// 特殊 xkType 排序逻辑
const reorderForXkType = (data, zyORyxList) => {
  const dominantId = getDominantItem(zyORyxList);

  // 分离出包含和不包含 1 或 4 的项
  const [containList, unContainList] = data.reduce(
    ([contain, uncontain], item) => {
      (item.id === 1 || item.id === 4 ? contain : uncontain).push(item);
      return [contain, uncontain];
    },
    [[], []],
  );

  // 重排列表，优先 dominantId 的项，然后是未包含的项，最后是其他包含项
  return [
    ...containList.filter((item) => item.id == dominantId),
    ...unContainList,
    ...containList.filter((item) => item.id != dominantId),
  ];
};

// 截取院校和专业包含物理和历史的选项（xkType == 3）
const extractAndFilter = (list) =>
  list
    .map((obj) => obj.bestCombine.split(',')[0]) // 提取第一个值
    .filter((value) => value === '1' || value === '4'); // 过滤值为 '1' 或 '4'

// 统计 "1" 和 "4" 的数量
const getDominantItem = (arr) => {
  const count1 = arr.reduce((count, item) => count + (item === '1'), 0);
  const count4 = arr.reduce((count, item) => count + (item === '4'), 0);
  return count1 === count4 ? arr[arr.length - 1] : count1 > count4 ? '1' : '4';
};
